const express = require('express');
// const multiparty = require('connect-multiparty');
// const multipartMiddleware = multiparty();
const app = express();
const fs = require('fs');
const path = require('path');
const http = require('http');
const ejs = require('ejs');
const https = require('https');
const bodyParser = require('body-parser');
const privateKey = fs.readFileSync('./cert/214566182980336.key');
const certificate = fs.readFileSync('./cert/214566182980336.pem');
const credentials = {key: privateKey, cert: certificate};

const httpServer = http.createServer(app);
// const httpsServer = https.createServer(credentials, app);
const PORT = 80;
// const SSLPORT = 443;

// app.get('/', function (req, res) {
//     res.redirect('/#/');
// });
app.set('views', path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

httpServer.listen(PORT, function () {
    console.log('HTTP Server is running on: http://localhost:%s', PORT);
});
// httpsServer.listen(SSLPORT, function () {
//     console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT);
// });

app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    // res.header("Access-Control-Allow-Headers", "X-Requested-With");
    // res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    // res.header("X-Powered-By", ' 3.2.1');
    // res.header("Content-Type", "application/json;charset=utf-8");
    res.data = function (data) {
        this.json({code: 200, data: data});
    };
    next();
});
// Welcome

require('./db/mongodb').load();
//拦截用户必须登陆才能访问其他路由
app.use(async function (req, res, next) {
    const url = req.originalUrl;
    const mongoose = require('mongoose');
    const UserModel = mongoose.models['User'];
    if (url.indexOf('/game/') >= 0 && url != "/game/login/checkLogin") {
        let user = await UserModel.findOne({openid: req.query.openid, token: req.query.token});
        if (!user) {
            return res.json({code: 500, msg: '未登陆不允许访问'});
        }
    }
    next();
});

const routes = require('./router/router');
routes(app);
app.use(function (err, req, res, next) {
    res.json({code: 500, msg: err});
});
app.use(function (req, res, next) {
    res.json({code: 500, msg: 'no such router'});
});

//启动后自动注册测试用户到数据库
require('./db/defaultData/registerDefaultWeChatUser');
require('./db/defaultData/registerDefaultAdmin');
require('./db/defaultData/registerDefaultDictionary');
require('./db/defaultData/registerDefaultJob');


// app.use(multiparty({uploadDir:'./public/upload/mp3' }));
//
// app.post('/upload',multipartMiddleware, function (req,res) {
//     let keys=Object.keys(req.files);
//     let source = fs.createReadStream(req.files[keys[0]].path);
//     let fileName=req.body.fileName;
//     let dest = fs.createWriteStream('public/upload/mp3/'+fileName);
//     source.pipe(dest);
//     source.on('end', function() { fs.unlinkSync(req.files[keys[0]].path);});   //delete
//     source.on('error', function(err) {  });
//     res.json({fileName:fileName});
// });
//
// //定时删除上传目录30分钟前的文件
// const schedule = require('node-schedule');
// schedule.scheduleJob('30 * * * * *', function(){
//     //console.log('定时删除文件任务运行:' + new Date());
//     let fileUrl='public/upload/mp3';
//     let files = fs.readdirSync(fileUrl);//读取该文件夹
//     let now=new Date().getTime();
//     files.forEach(function(file){
//         var stats = fs.statSync(fileUrl+'/'+file);
//         if(now-stats.atime.getTime()>60000){
//             fs.unlinkSync(fileUrl+'/'+file);
//             console.log("定时删除文件"+fileUrl+'/'+file+"成功");
//         }
//     });
// });